﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using WebShopData;

namespace WebShop_Project
{
    public partial class Products : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        private static void AddItemToShoppingCart(List<ShoppingCartItem> shoppingCartItems, int articleID)
        {
            try
            {
                if (shoppingCartItems != null)
                {
                    var foundShoppingCartItem =
                        shoppingCartItems.Find(article => article.Article.ArticleID == articleID);

                    if (foundShoppingCartItem == null)
                    {
                        var shoppingCartItem = new ShoppingCartItem(Articles.GetArticle(articleID));
                        shoppingCartItems.Add(shoppingCartItem);
                    }
                    else
                    {
                        foundShoppingCartItem.Quantity += 1;
                    }
                }
                else
                {
                    var shoppingCartItem = new ShoppingCartItem(Articles.GetArticle(articleID));
                    shoppingCartItems.Add(shoppingCartItem);
                }
            }
            catch (Exception ex)
            {
                DBException.AddException(ex.Message, ex.GetType().ToString());
            }
        }

        protected void ListViewArticles_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                ListViewDataItem dataItem = (ListViewDataItem)e.Item;
                int articleID = int.Parse(ListViewArticles.DataKeys[dataItem.DisplayIndex].Value.ToString());

                var shoppingCartItems = (List<ShoppingCartItem>)Session["ShoppingCart"];
                AddItemToShoppingCart(shoppingCartItems, articleID);
                Session["ShoppingCart"] = shoppingCartItems;
                Response.Redirect("products.aspx");
            }
            catch (Exception ex)
            {
                DBException.AddException(ex.Message, ex.GetType().ToString());
            }

        }
    }
}